import {
  apiCmsmqGetBuyList,
  cmsmeCmsmeVoList,
  cmsmqGetCustomList,
  cmsmvBusinessmanList,
  cmsnaCmsnaVoList,
  copmaList,
  copmdGetAddressByCustomId,
  coptcAdd,
  coptcSelectTc002,
  latestExchangeRate,
} from '@/api/url/salesOrderManagement';
import { onMounted, reactive } from 'vue';
import { coptcDom, ephemeralData, dataInteractionMechanism, coptdDom, coptdDomInfoChange } from './base/base';
import { deepCopy, formatDate, isNullPm } from '@/utils/baseMethods';
import { VXETable } from 'vxe-table';
import XEClipboard from 'xe-clipboard';
import { multiplication, relativeAddition, subtraction } from '@/utils/calculationFormula';
import notification from '@arco-design/web-vue/es/notification';
import router from '@/router';
import { isLocal } from '@/utils/auth';

export default function importConfig() {
  const base = reactive<any>({
    fromDom: null,
    purchaseDom: null,
    coptcDom: null,
    customerDom: null,
    ephemeralData: null,
    adderList: [],
    departmentList: [],
    salesman: [],
    salesmanList: [],
    paymentList: [],
    coptdList: [],
    visible: false,
    title: null,
    modelWidth: 1000,
    orderInfo: null,
    customList: null,
    exchangeRate: 1,
    emptyInfo: {},
    customerModalVisible: false,
    type: '',
    fileListDtp: [],
  });

  const init = () => {
    purchaseOrderOption();
    base.coptcDom = coptcDom();
    base.emptyInfo = coptcDom();
    base.ephemeralData = ephemeralData;
    fundamentalOperation();
    customerInformation();
    departmentPullDown();
    salesmanOption();
    paymentOption();
    base.coptdList = [coptdDom()];
    // localStorage.removeItem('ITEMDOM');
    // localStorage.removeItem('customerNumData');
    localStorage.removeItem('customerId');
    itemNumberInformation();
  };

  /**
   * @exports purchaseOrderOption 采购单别下拉数据接口
   */
  const purchaseOrderOption = () => {
    cmsmqGetCustomList().then((res: any) => {
      if (res.code == '200') base.purchaseDom = res.data;
    });
  };

  /**
   * @exports fundamentalOperation 基础操作
   */
  const fundamentalOperation = () => {
    base.coptcDom.tc003 = formatDate(new Date(), 'yyyy-MM-dd');
    base.coptcDom.tc039 = formatDate(new Date(), 'yyyy-MM-dd');
    base.coptcDom.tci01 = formatDate(new Date(), 'yyyy-MM-dd');
    base.coptcDom.tci02 = formatDate(new Date(), 'yyyy-MM-dd');
    base.coptcDom.TCI02 = formatDate(new Date(), 'yyyy-MM-dd');
    base.coptcDom.UDF03 = formatDate(new Date(), 'yyyy-MM-dd');
  };

  /**
   * @exports noChangechsc 采购单别下拉数据接口
   */
  const noChangechsc = (param: any) => {
    const steam = {
      tc001: param,
    };
    base.coptcDom.tc002 = null;
    if (!isNullPm(steam.tc001))
      coptcSelectTc002(steam).then((res: any) => {
        base.coptcDom.tc002 = res.data;
      });
  };

  /**
   * @exports customerInformation 客户信息下拉接口
   */
  const customerInformation = () => {
    copmaList('').then((res: any) => {
      if (res.code == 200) {
        base.customerDom = res.data;
      }
    });
  };

  /**
   * @exports customerOption 客户编号被选择时,绑定默认的数据
   */
  const customerOption = (param, index) => {
    if (isLocal('ITEMDOM')) localStorage.removeItem('ITEMDOM');
    if (isLocal('customerNumData')) localStorage.removeItem('customerNumData');
    base.coptdList = [coptdDom()];
    if (index == 1) {
      base.ephemeralData.customerName = param.ma002;
      base.coptcDom.tc004 = param.ma001;
      dataInteractionMechanism().map((res: any) => {
        if (res.identifier) base.coptcDom[res.swop] = param[res.value];
        else base.coptcDom[res.swop] = res.value;
      });
      base.adderList = [param?.ma027];
      base.coptcDom.tc010 = param?.ma027;
      base.coptcDom.tc011 = param?.ma027;
      userAdderOption(param.ma001);
    } else if (index == 2) {
      base.coptcDom.udf03 = param.ma002;
      base.coptcDom.udf05 = param?.ma027;
    }
    changeCurrency(param.ma014);
  };

  /**
   * @exports departmentPullDown 部门下拉接口
   */
  const departmentPullDown = () => {
    base.departmentList = [];
    cmsmeCmsmeVoList().then((res: any) => {
      if (res.code == '200') base.departmentList = res.data;
    });
  };

  /**
   * @exports salesmanOption 业务员下拉
   */
  const salesmanOption = () => {
    cmsmvBusinessmanList().then((res: any) => {
      if (res.code == '200') {
        base.salesman = res.data;
        base.salesman.map((reb: any) => {
          Object.keys(reb).map((rea: any) => {
            reb[rea] = reb[rea].trim();
          });
        });
        base.salesmanList = JSON.parse(JSON.stringify(base.salesman));
      }
    });
  };

  /**
   * @exports salesmanChange 通过部门选择员工
   */
  const salesmanChange = (param) => {
    base.salesmanList = [];
    base.salesman.map((res: any) => {
      if (res.mv004 == param) base.salesmanList.push(res);
    });
  };

  /**
   * @exports paymentOption 付款条件下拉
   */
  const paymentOption = () => {
    cmsnaCmsnaVoList().then((res: any) => {
      if (res.code == '200') base.paymentList = res.data;
    });
  };

  const menuConfig = reactive({
    className: 'my-menus',
    header: {
      options: [[{ code: 'exportAll', name: '导出所有.csv' }]],
    },
    body: {
      options: [
        [{ code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy', className: 'my-copy-item' }],
        [
          { code: 'remove', name: '删除', prefixIcon: 'vxe-icon-delete-fill color-red' },
          {
            name: '筛选',
            children: [
              { code: 'clearFilter', name: '清除筛选' },
              { code: 'filterSelect', name: '按所选单元格的值筛选' },
            ],
          },
          {
            code: 'sort',
            name: '排序',
            prefixIcon: 'vxe-icon-sort color-blue',
            children: [
              { code: 'clearSort', name: '清除排序' },
              { code: 'sortAsc', name: '升序', prefixIcon: 'vxe-icon-sort-alpha-asc color-orange' },
              { code: 'sortDesc', name: '倒序', prefixIcon: 'vxe-icon-sort-alpha-desc color-orange' },
            ],
          },
          { code: 'print', name: '打印', disabled: true },
        ],
      ],
    },
    footer: {
      options: [[{ code: 'clearAll', name: '清空数据' }]],
    },
  });

  const contextMenuClickEvent = ({ menu, row, column, rowIndex }) => {
    switch (menu.code) {
      case 'copy':
        // 示例
        if (row && column) {
          if (XEClipboard.copy(row[column.field])) {
            VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
          }
        }
        break;
      case 'remove':
        if (base.coptdList.length == 1) {
          base.coptdList = [coptdDom()];
          break;
        }

        const ITEMDOM: any = localStorage.getItem('ITEMDOM');
        const customerNumData: any = localStorage.getItem('customerNumData');

        if (isNullPm(ITEMDOM) && isNullPm(customerNumData)) return false;
        let steamDomA: any = null;
        let steamDomB: any = null;
        const steamDom: any = null;
        if (!isNullPm(ITEMDOM)) steamDomA = JSON.parse(ITEMDOM);
        if (!isNullPm(customerNumData)) steamDomB = JSON.parse(customerNumData);

        let muncon: any = null;
        let munconsaa: any = null;
        if (row.dataSouer == 'PH')
          steamDomA.selectionRows.map((reb: any, keya: any) => {
            reb?.map((rec: any, index: any) => {
              if (rec.id == row.id) {
                muncon = index;
                munconsaa = keya;
              }
            });
          });
        else
          steamDomB.selectionRows.map((reb: any, keya: any) => {
            reb?.map((rec: any, index: any) => {
              if (rec.id == row.id) {
                muncon = index;
                munconsaa = keya;
              }
            });
          });

        if (!isNullPm(muncon)) {
          if (row.dataSouer == 'PH') steamDomA.selectionRows[munconsaa].splice(muncon, 1);
          else steamDomB.selectionRows[munconsaa].splice(muncon, 1);
        }
        if (row.dataSouer == 'PH') localStorage.setItem('ITEMDOM', JSON.stringify(steamDomA));
        else localStorage.setItem('customerNumData', JSON.stringify(steamDomB));
        base.coptdList.splice(rowIndex, 1);
        base.coptdList.sort();
        break;
      default:
        VXETable.modal.alert(`点击了 ${menu.name} 选项`);
    }
  };

  /**
   * @exports modelOpen 模态框打开操作
   * @param param
   */
  const modelOpen = (param): any => {
    if (isNullPm(base.coptcDom.tc004)) {
      VXETable.modal.alert(`请先选择客户编号`);
      return false;
    }
    localStorage.setItem('customerId', base.coptcDom.tc004);
    if (param == '品号查询') {
      base.title = param;
      base.visible = true;
    } else if (param == '客户品号查询') {
      base.customerModalVisible = true;
    }
  };

  /**
   * @exports handleOk 模态框确认操作
   */
  const handleOk = () => {
    base.type = 'productNum';
    if (base.title == '品号查询') itemNumberInformation();
  };

  /**
   * @exports itemNumberInformation 品号信息载入器
   */
  const itemNumberInformation = (): any => {
    const ITEMDOM: any = localStorage.getItem('ITEMDOM');
    const customerNumData: any = localStorage.getItem('customerNumData');

    if (isNullPm(ITEMDOM) && isNullPm(customerNumData)) return false;
    let steamDomA = [];
    let steamDomB = [];
    let steamDom: any = null;
    if (!isNullPm(ITEMDOM)) steamDomA = JSON.parse(ITEMDOM).selectionRows;
    if (!isNullPm(customerNumData)) steamDomB = JSON.parse(customerNumData).selectionRows;
    steamDomA?.map((res: any) => {
      res.map((reb: any) => {
        reb.dataSouer = 'PH';
      });
    });
    steamDomB?.map((res: any) => {
      res.map((reb: any) => {
        reb.dataSouer = 'KHPH';
      });
    });
    steamDom = steamDomA.concat(steamDomB);
    base.coptdList = [];
    steamDom.map((reb: any) => {
      reb?.map((res: any) => {
        const steann: any = coptdDom();
        res.mb111 = multiplication({ x: 100, y: res.mb111 });
        coptdDomInfoChange().map((rea: any) => {
          steann[rea.swop] = res[rea.value];
        });
        steann.id = res.id;
        base.coptdList.push(steann);
      });
    });

    orderInfoLoad();
  };

  /**
   * @exports orderInfoLoad 订单信息载入
   */
  const orderInfoLoad = () => {
    //  订单金额 | 订单税额 | 合计 | 包装总数量 |
    //  订单本币金额 | 订单本币税额 | 订单本币合计
    //  总数量 | 总体积(CUFT)
    /**
     * @param orderAmount 订单金额
     * @param orderTax 订单税额
     * @param total 合计
     * @param totalPackageQuantity 包装总数量
     * @param orderAmountLocalCurrency 订单本币金额
     * @param domesticTaxOnOrders 订单本币税额
     * @param totalOrdersLocalCurrency 订单本币合计
     * @param totalQuantity 总数量
     * @param bulkVolume 总体积
     */
    const steam: any = {
      orderAmount: 0,
      orderTax: 0,
      total: 0,
      totalPackageQuantity: 0,
      orderAmountLocalCurrency: 0,
      domesticTaxOnOrders: 0,
      totalOrdersLocalCurrency: 0,
      totalQuantity: 0,
      bulkVolume: 0,
    };
    Object.keys(steam).map((res: any) => {
      steam[res] = 0;
    });

    base.coptdList.map((res: any) => {
      steam.orderAmount = relativeAddition({ x: steam.orderAmount, y: res.td012 });
      steam.orderTax = relativeAddition({ x: steam.orderTax, y: res.td039 });
      steam.total = relativeAddition({ x: steam.total, y: res.td012 });
      steam.totalPackageQuantity = relativeAddition({ x: steam.totalPackageQuantity, y: res.td032 });
      steam.orderAmountLocalCurrency = relativeAddition({ x: steam.orderAmountLocalCurrency, y: res.tdi03 });
      steam.domesticTaxOnOrders = relativeAddition({ x: steam.domesticTaxOnOrders, y: res.tdi02 });
      steam.totalOrdersLocalCurrency = relativeAddition({
        x: steam.totalOrdersLocalCurrency,
        y: relativeAddition({ x: res.tdi02, y: res.tdi03 }) as any,
      });
      steam.totalQuantity = relativeAddition({ x: steam.totalQuantity, y: res.td008 });
      steam.bulkVolume = relativeAddition({ x: steam.bulkVolume, y: res.td031 });
    });
    base.orderInfo = [
      {
        label: '订单金额',
        value: steam.orderAmount,
      },
      {
        label: '订单税额',
        value: steam.orderTax,
      },
      {
        label: '合计',
        value: steam.total,
      },
      {
        label: '包装总数量',
        value: steam.totalPackageQuantity,
      },
      {
        label: '订单本币金额',
        value: steam.orderAmountLocalCurrency,
      },
      {
        label: '订单本币税额',
        value: steam.domesticTaxOnOrders,
      },
      {
        label: '订单本币合计',
        value: steam.totalOrdersLocalCurrency,
      },
      {
        label: '总数量',
        value: steam.totalQuantity,
      },
      {
        label: '总体积',
        value: steam.bulkVolume,
      },
    ];
    base.coptdList.sort();
  };

  /**
   * @exports dataComputationLoad 表单数据变动时,同时计算表单数据变化
   */
  const dataComputationLoad = (rowIndex) => {
    debouncedFunction(rowIndex);
  };
  /**
   * @exports debouncedFunction 防抖集成
   */
  const debouncedFunction = debounce((rowIndex) => {
    computationHook(rowIndex);
  }, 300);
  /**
   * @exports computationHook 计算钩子
   */
  const computationHook = (rowIndex) => {
    /**
     * 订单金额计算
     */
    base.coptdList[rowIndex].td012 = orderAmountCalculation(base.coptdList[rowIndex], '原币');
    base.coptdList[rowIndex].tdi03 = orderAmountCalculation(base.coptdList[rowIndex], '本币');
    /**
     * 税前金额计算
     */
    base.coptdList[rowIndex].td038 = preTaxCalculation(base.coptdList[rowIndex], '原币');
    base.coptdList[rowIndex].tdi01 = preTaxCalculation(base.coptdList[rowIndex], '本币');
    /**
     * 税额计算
     */
    base.coptdList[rowIndex].td039 = taxCalculation(base.coptdList[rowIndex], '原币');
    base.coptdList[rowIndex].tdi02 = taxCalculation(base.coptdList[rowIndex], '本币');
    orderInfoLoad();
  };
  /**
   * @exports singleRecalculation 单身数据重新计算
   */
  const singleRecalculation = () => {
    base.coptdList.map((res: any, index) => {
      computationHook(index);
    });
  };

  /**
   * @exports orderAmountCalculation 订单金额计算器
   */
  const orderAmountCalculation = (steam, param) => {
    const steamTD037: any = multiplication({ x: steam.td037, y: 0.01 });
    /**
     * @exports totalAmount 总金额
     */
    const totalAmount: any = multiplication({ x: steam.td011, y: steam.td008 });
    /**
     * @exports taxAmount 税额
     */
    const taxAmount: any = multiplication({ x: totalAmount, y: steamTD037 });
    if (param == '原币') {
      if (base.coptcDom.tc016 == '1') return totalAmount;
      else if (base.coptcDom.tc016 == '2') return relativeAddition({ x: totalAmount, y: taxAmount });
      else return totalAmount;
    } else {
      const USDTotalAmount: any = multiplication({ x: base.coptcDom.tc009, y: totalAmount });
      const USDtaxAmount: any = multiplication({ x: taxAmount, y: base.coptcDom.tc009 });
      if (base.coptcDom.tc016 == '1') return USDTotalAmount;
      else if (base.coptcDom.tc016 == '2') return relativeAddition({ x: USDTotalAmount, y: USDtaxAmount });
      else return USDTotalAmount;
    }
  };

  /**
   * @exports preTaxCalculation 税前金额计算器
   * @param steam
   * @returns
   */
  const preTaxCalculation = (steam, param) => {
    const steamTD037: any = multiplication({ x: steam.td037, y: 0.01 });
    /**
     * @exports totalAmount 总金额
     */
    const totalAmount: any = multiplication({ x: steam.td011, y: steam.td008 });
    /**
     * @exports taxAmount 税额
     */
    const taxAmount: any = multiplication({ x: totalAmount, y: steamTD037 });
    if (param == '原币') {
      if (base.coptcDom.tc016 == '1') return subtraction({ x: totalAmount, y: taxAmount });
      else if (base.coptcDom.tc016 == '2') return totalAmount;
      else return totalAmount;
    } else {
      const USDTotalAmount: any = multiplication({ x: base.coptcDom.tc009, y: totalAmount });
      const USDtaxAmount: any = multiplication({ x: taxAmount, y: base.coptcDom.tc009 });
      if (base.coptcDom.tc016 == '1') return subtraction({ x: USDTotalAmount, y: USDtaxAmount });
      else if (base.coptcDom.tc016 == '2') return USDTotalAmount;
      else return USDTotalAmount;
    }
  };
  /**
   * @exports taxCalculation 税额计算器
   * @param steam
   * @returns
   */
  const taxCalculation = (steam: any, param) => {
    // td011 单价
    // td008 数量
    // td037 税率
    const steamTD037: any = multiplication({ x: steam.td037, y: 0.01 });
    if (['1', '2'].includes(base.coptcDom.tc016))
      if (param == '原币') return multiplication({ x: multiplication({ x: steam.td011, y: steam.td008 }) as any, y: steamTD037 });
      else
        return multiplication({
          x: base.coptcDom.tc009,
          y: multiplication({ x: multiplication({ x: steam.td011, y: steam.td008 }) as any, y: steamTD037 }) as any,
        });
    else return 0;
  };

  /**
   * @exports debounce 防抖代码
   * @param func
   * @param delay
   * @returns
   */
  function debounce<T extends (...args: any[]) => void>(func: T, delay: number) {
    let timeoutId: any;

    return function (this: ThisParameterType<T>, ...args: Parameters<T>) {
      const context = this;

      const later = () => {
        timeoutId = null;
        func.apply(context, args);
      };

      clearTimeout(timeoutId);
      timeoutId = setTimeout(later, delay);
    };
  }

  /**
   * @exports addOption 添加客户订单接口
   */
  const addOption = (): any => {
    const steam = {
      coptc: deepCopy(base.coptcDom),
      coptdList: deepCopy(base.coptdList),
      creator: 'ERP',
    };
    Object.keys(steam.coptc).map((res: any) => {
      if (!isNullPm(steam.coptc[res]) && typeof steam.coptc[res] == 'string') {
        if (steam.coptc[res].indexOf('-') != -1) steam.coptc[res] = steam.coptc[res].replace(/-/g, '');
      }
    });
    steam.coptdList.map((res: any, index: any) => {
      if (!isNullPm(res.td013)) res.td013 = res.td013.replace(/-/g, '');
      if (!isNullPm(res.udf03)) res.udf03 = res.udf03.replace(/-/g, '');
      res.td001 = steam.coptc.tc001;
      res.td002 = steam.coptc.tc002;
      res.td037 = multiplication({ x: res.td037, y: 0.01 });
      delete res.no;
      delete res.mc002;
      delete res.mg005;
      delete res.mg006;
      delete res.mb443;
      delete res._X_ROW_KEY;
      delete res.id;
    });
    if (!isNullPm(base.orderInfo)) {
      steam.coptc.tc029 = base.orderInfo[0]?.value;
      steam.coptc.tc031 = base.orderInfo[2]?.value;
    }
    if (isNullPm(steam.coptc.tc001) || isNullPm(steam.coptc.tc002)) {
      notification.error('订单单别不允许为空');
      return false;
    }
    if (isNullPm(steam.coptc.tc004)) {
      notification.error('客户编号不能为空');
      return false;
    }
    if (isNullPm(steam.coptc.tc006)) {
      notification.error('业务人员不能为空');
      return false;
    }
    if (isNullPm(steam.coptc.tc005)) {
      notification.error('业务部门不能为空');
      return false;
    }
    if (steam.coptdList.length == 1 && isNullPm(steam.coptdList[0]?.td004)) {
      notification.error('商品信息中至少要有一条数据');
      return false;
    }

    coptcAdd(steam).then((res: any) => {
      if (res.code == 200) {
        localStorage.removeItem('customerNumData');
        localStorage.removeItem('customerId');
        notification.info('添加成功');
        localStorage.removeItem('ITEMDOM');
        router.push('salesOrder');
      } else {
        notification.error('添加失败');
      }
    });
  };

  /**
   * @exports sequenceNumberGenerator 序号生气器
   * @param index
   * @returns
   */
  const sequenceNumberGenerator = (index) => {
    if (index < 10) return '000' + (index + 1);
    else if (index < 100) return '00' + (index + 1);
    else return '0' + (index + 1);
  };

  /**
   * @exports userAdderOption 收货地址
   */
  const userAdderOption = (param) => {
    copmdGetAddressByCustomId(`?customId=${param}`).then((res: any) => {
      if (res.code == 200) {
        const arr: any = [];
        res.data.forEach((item) => {
          arr.push(item.addressNameOne);
        });
        base.customList = arr;
      }
    });
  };

  /**
   * @exports getCurrency 获取汇率
   */
  const getCurrency = () => {
    latestExchangeRate('USD').then((res) => {
      if (res.code == 200) {
        base.exchangeRate = res.data;
      }
    });
  };

  //切换币种
  const changeCurrency = (currency) => {
    if (currency == 'USD') {
      base.coptcDom.tc009 = base.exchangeRate;
    } else if (currency == 'RMB') {
      base.coptcDom.tc009 = 1;
    }
    singleRecalculation();
  };

  //客户品号确定
  const handleOkCustomerOk = () => {
    base.type = 'customerNum';
    itemNumberInformation();
    base.customerModalVisible = true;
  };

  const handleCustomerCancel = () => {
    base.customerModalVisible = false;
  };

  onMounted(() => {
    // if (isLocal('ITEMDOM')) localStorage.removeItem('ITEMDOM');
    // if (isLocal('customerNumData')) localStorage.removeItem('customerNumData');
    getCurrency();
  });

  const filelist = (param) => {
    console.log(param, '==>iooiio');
    base.fileListDtp = [];
    param.map((res: any) => {
      base.fileListDtp.push(res.filePm);
    });
  };
  return {
    base,
    init,
    noChangechsc,
    customerOption,
    salesmanChange,
    paymentOption,
    menuConfig,
    contextMenuClickEvent,
    modelOpen,
    handleOk,
    dataComputationLoad,
    addOption,
    changeCurrency,
    handleOkCustomerOk,
    handleCustomerCancel,
    singleRecalculation,
    filelist,
  };
}
